package xyz.weblade.lynchmybatis;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JdbcPreparedStatementExample {
    
    // 数据库连接信息
    private static final String URL = "jdbc:mysql://localhost:3306/yeecode";
    private static final String USER = "root";
    private static final String PASSWORD = "iamapig";
    
    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        
        try {
            // 1. 加载驱动 (JDBC 4.0+ 可以自动加载，此步可省略)
            Class.forName("com.mysql.cj.jdbc.Driver");
            
            // 2. 获取数据库连接
            connection = DriverManager.getConnection(URL, USER, PASSWORD);
            
            // 3. 准备SQL语句，使用?作为参数占位符
            String sql = "SELECT * FROM user WHERE id= 1";
            
            // 4. 创建PreparedStatement对象
            preparedStatement = connection.prepareStatement(sql);

            
            // 6. 执行查询，获取结果集
           preparedStatement.executeQuery();
            resultSet = preparedStatement.getResultSet();
            // 7. 处理结果集
            while (resultSet.next()) {
                // 通过列名获取值
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                int age = resultSet.getInt("age");
                
                // 也可以通过列索引获取值 (索引从1开始)
                // int id = resultSet.getInt(1);
                // String name = resultSet.getString(2);
                // int age = resultSet.getInt(3);
                
                System.out.printf("ID: %d, Name: %s, Age: %d%n", id, name, age);
            }
            
        } catch (ClassNotFoundException e) {
            System.err.println("找不到数据库驱动: " + e.getMessage());
        } catch (SQLException e) {
            System.err.println("数据库操作异常: " + e.getMessage());
        } finally {
            // 8. 关闭资源 (按ResultSet → Statement → Connection的顺序)
            try {
                if (resultSet != null) resultSet.close();
                if (preparedStatement != null) preparedStatement.close();
                if (connection != null) connection.close();
            } catch (SQLException e) {
                System.err.println("关闭资源时出错: " + e.getMessage());
            }
        }
    }
}